const routes = [
  {
   path: '/',
   redirect: '/layout'
  },
  {
   path: '/layout',
   component: (resolve) => require(['../layout.vue'], resolve),
   children: []
  }
 ]
 export default {
  /**
   * 合并主菜单和子菜单
   * @param: rootList [Array] 主菜单列表
   * @param: subList [Array] 子菜单
   * */
  mergeSubInRoot (roots, subs) {
   if (roots && subs) {
    for (let i = 0; i < roots.length; i++) {
     let rootCode = roots[i].code
     roots[i].children = []
     for (let j = 0; j < subs.length; j++) {
      if (rootCode === subs[j].code.substring(0, 4)) {
       roots[i].children.push(subs[j])
      }
     }
    }
   }
   return roots
  },
  /**
   * 合并远程路由到本地路由
   * @param: subList [Array] 远程路由列表
   * @param: routes [Array] 本地路由列表
   * */
  mergeRoutes (subs) {
   if (subs) {
    for (let i = 0; i < subs.length; i++) {
     let temp = {
      path: subs[i].actUrl,
      name: subs[i].actUrl,
      component: (resolve) => require([`@/components/${subs[i].component}.vue`], resolve),
      meta: {
       type: subs[i].type,
       code: subs[i].code,
       title: subs[i].name,
       permissionList: subs[i].permissionList
      }
     }
     routes[1].children.push(temp)
    }
   }
   return routes
  }
 }




 login () {
  let params = {
   account: this.loginForm.username,
   password: encrypt(this.loginForm.password)
  }
  this.loading = true
  this.$http.post(this.$bumng + '/login', this.$HP(params))
   .then((res) => {
    this.loging = false
    console.info('菜单列表：', res)
    if (res.resultCode === this.$state_ok) {
     // 合并一级菜单和二级菜单，便于显示
     let menus = handleMenu.mergeSubInRoot(res.rootList, res.subList)
     // 本地化处理好的菜单列表
     this.saveRes({label: 'menuList', value: menus})
     // 根据subList处理路由
     let routes = handleMenu.mergeRoutes(res.subList)
     // 本地化subList，便于在刷新页面的时候重新配置路由
     this.saveRes({label: 'subList', value: res.subList})
     // 防止重复配置相同路由
     if (this.$router.options.routes.length <= 1) {
      this.$router.addRoutes(routes)
      // this.$router不是响应式的，所以手动将路由元注入路由对象
      this.$router.options.routes.push(routes)
     }
     this.$router.replace('/layout/index')
    }
   })
   .catch((err) => {
    this.loging = false
    console.error('错误：', err)
   })
 },